<?php

namespace App\Http\Controllers;

use App\Models\Employee;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class UserController extends Controller
{

    protected $ttl = 120;
    protected $isCry = 1;

    /**
     * 显示给定用户的配置文件。
     * @param string $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|View
     */
    public function show(string $id)
    {
        $token = csrf_token();
        $token1 = $this->isCry == 1 ? Crypt::encryptString($token) : '';
        Cache::store('redis')->put('ucs_token', $token1, $this->ttl);
        return view('user', [
            'name' => '用户列表' . $this->isCry,
            'id'   => $id
        ]);
    }

    public function getToken()
    {
        $token = csrf_token();
        $data = [
            'code'    => 200,
            'message' => 'success',
            'data'    => [
                'token' => $token
            ],

        ];
        return response()->json($data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList(Request $request)
    {
        $page_size = $request->get('page_size');
        $page = $request->get('page');
//        $cache_data = Cache::store('redis')->get('ucs_token');
//        $value = !empty($cache_data) ? $this->isCry == 1 ? Crypt::decryptString($cache_data) : '' : 'null';
        $list = Employee::query()->orderByDesc('id')->simplePaginate($page_size, ['*'], 'page', $page);
        $data = [
            'code'    => 200,
            'message' => 'success',
            'data'    => $list,

        ];
        return response()->json($data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        $ret = 0;
        $params = $request->post();
        foreach ($params as $val) {
            $model = new Employee();
            $model->uname = $val['uname'];
            $model->age = $val['age'];
            $model->save();
            $ret++;
        }
        $data = [
            'code'    => 200,
            'message' => 'success',
            'data'    => $ret,

        ];
        return response()->json($data);
    }

    /**
     * @param string $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        $ids = $request->input('ids');
        $result = Employee::destroy($ids);
        $data = [
            'code'    => 200,
            'message' => 'success',
            'data'    => $result,

        ];
        return response()->json($data);
    }
}
